package com.zhentao.equipment.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.equipment.mapper.DeviceGroupMapper;
import com.zhentao.equipment.mapper.DeviceGroupRelationMapper;
import com.zhentao.pojo.DeviceGroup;
import com.zhentao.pojo.DeviceGroupRelation;
import com.zhentao.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 分组管理服务：提供分组CRUD、分组树、设备绑定
 */
@Service
public class DeviceGroupService {

    @Autowired
    private DeviceGroupMapper groupMapper;

    @Autowired
    private DeviceGroupRelationMapper relationMapper;

    /** 新增或更新分组 */
    public ResultVo save(DeviceGroup group) {
        if (group.getGroupId() == null) {
            groupMapper.insert(group);
        } else {
            groupMapper.updateById(group);
        }
        return ResultVo.success();
    }

    /** 删除分组（同时删除绑定关系） */
    public ResultVo delete(Long groupId) {
        relationMapper.delete(new LambdaQueryWrapper<DeviceGroupRelation>().eq(DeviceGroupRelation::getGroupId, groupId));
        groupMapper.deleteById(groupId);
        return ResultVo.success();
    }

    /** 分组树 */
    public ResultVo tree() {
        List<DeviceGroup> list = groupMapper.selectList(null);
        Map<Long, List<DeviceGroup>> parentMap = list.stream().collect(Collectors.groupingBy(g -> g.getParentId() == null ? 0L : g.getParentId()));
        List<Map<String, Object>> tree = buildTree(parentMap, 0L);
        return ResultVo.success(tree);
    }

    private List<Map<String, Object>> buildTree(Map<Long, List<DeviceGroup>> parentMap, Long pid) {
        List<DeviceGroup> children = parentMap.getOrDefault(pid, Collections.emptyList());
        List<Map<String, Object>> nodes = new ArrayList<>();
        for (DeviceGroup g : children) {
            Map<String, Object> n = new HashMap<>();
            n.put("groupId", g.getGroupId());
            n.put("groupName", g.getGroupName());
            n.put("parentId", g.getParentId());
            n.put("children", buildTree(parentMap, g.getGroupId()));
            nodes.add(n);
        }
        return nodes;
    }

    /** 绑定一个分组的设备（覆盖式绑定） */
    public ResultVo bindDevices(Long groupId, List<Long> deviceIds) {
        relationMapper.delete(new LambdaQueryWrapper<DeviceGroupRelation>().eq(DeviceGroupRelation::getGroupId, groupId));
        if (deviceIds != null && !deviceIds.isEmpty()) {
            for (Long did : deviceIds) {
                DeviceGroupRelation r = new DeviceGroupRelation();
                r.setGroupId(groupId);
                r.setDeviceId(did);
                r.setCreateTime(new Date());
                relationMapper.insert(r);
            }
        }
        return ResultVo.success();
    }
}





